<template>
  <div ref="travelSpotRef" class="mobile-travel-view common-mobile-view">
    <travel-query />

    <div class="travel-list">
      <el-empty v-if="travelStore.travelSpotList.length === 0" description="暂无旅行记录"/>

      <div v-else class="list">
        <travel-card v-for="(item, index) in travelStore.travelSpotList"
                     :key="index" :travel-item="item"/>
      </div>
    </div>

    <draggable-button @click="addClick"/>

    <arrive-bottom v-if="travelStore.isScrollEnd"/>
  </div>
</template>

<script lang="ts" setup>
import TravelQuery from '@/components/Travel/TravelQuery.vue'
import ArriveBottom from '@/components/Common/ArriveButton.vue'
import { onBeforeUnmount, onMounted, ref } from 'vue'
import TravelCard from '@/components/Travel/TravelCard.vue'
import { useTravelStore } from '@/store/travel.ts'
import DraggableButton from '@/components/Common/DraggableButton.vue'
import { useRouter } from 'vue-router'

const travelStore = useTravelStore()
const router = useRouter()

const travelSpotRef = ref()

onMounted(async () => {
  travelStore.pageInfo = {
    currentPage: 1,
    pageSize: 3,
    totalSize: 1
  }
  travelStore.travelSpotList = []
  await travelStore.queryMobileTravelSpotList()
  travelSpotRef.value.addEventListener('scroll', handleScroll)
})

onBeforeUnmount(() => {
  travelSpotRef.value.removeEventListener('scroll', handleScroll)
})

const handleScroll = () => {
  const el = travelSpotRef.value
  if (el.scrollTop + el.clientHeight >= el.scrollHeight - 10) {
    const { currentPage, pageSize, totalSize } = travelStore.pageInfo
    travelStore.isScrollEnd = pageSize * currentPage > totalSize
    if (!travelStore.isScrollEnd) {
      travelStore.pageInfo.currentPage++
      travelStore.queryMobileTravelSpotList()
    }
  }
}

const addClick = () => {
  travelStore.travelSpotApiType = 'ADD'
  travelStore.currentTravelSpot = travelStore.getEmptyTravelSpot()
  router.push({ name: 'TravelSpotForm' })
}
</script>

<style lang="scss">
@use "@/styles/home/travel.mobile.module";
</style>
